﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using AttributeRouting.Web.Mvc;
using Microsoft.Ajax.Utilities;
using Newtonsoft.Json;
using TemperatureDatabase;

namespace MvcWebRole1.Controllers
{
    [OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)]
    public class MeasurementsController : Controller
    {
        

        [GET("Measurements/Get/{id:int}/{amount:int}/")]
        public string GetDays(int id, int amount)
        {
            if (amount == 0)
            {
                return Get(id, 10);
            }

            var timezone = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
            var timestamp = TimeZoneInfo.ConvertTime(DateTime.Now,timezone);
            var timeLimit = timestamp - TimeSpan.FromDays(amount);
            string result;

            using (var db = new TemperatureDBEntities())
            {
                var measurements = db.Measurement.Where(x => x.SensorId == id && x.Timestamp > timeLimit).ToList();
                var grouped = measurements.GroupBy(x => x.Timestamp.Date);
                var measurementList = new List<Measurement>();

                foreach (var day in grouped)
                {
                    measurementList.Add(new Measurement
                    {
                        Timestamp = day.First().Timestamp.Date,
                        Temperature = day.Average(x => x.Temperature)
                    });
                }

                result = JsonConvert.SerializeObject(measurementList);
            }
            
            

            return result;
        }

        //[GET("Measurements/Flush")]
        //public string Flush()
        //{
        //    using (var db = new TemperatureDBEntities())
        //    {
        //        db.Database.ExecuteSqlCommand("DELETE FROM Measurement");
        //        db.SaveChanges();
        //    }
        //    return "success";
        //}

        [GET("Measurements/GetAmount/{id:int}/{amount:int}/")]
        public string Get(int id, int amount)
        {
            List<Measurement> measurements;

            using (var db = new TemperatureDBEntities())
            {
                measurements = db.Measurement.Where(x => x.SensorId == id)
                                             .OrderByDescending(y => y.Timestamp)
                                             .Take(amount)
                                             .ToList();
            }
            measurements = measurements.OrderBy(x => x.Timestamp).ToList();
            var result = JsonConvert.SerializeObject(measurements);

            return result;
        }


    }
}
